/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kimstore.gui.items;

import com.kimstore.bean.Customer;
import com.kimstore.gui.sales.*;
import com.kimstore.bean.Item;
import com.kimstore.bean.ItemStatus;
import com.kimstore.bean.Staff;
import com.kimstore.factory.DaoFactory;
import com.kimstore.main.controller.CustomerTabController;
import com.kimstore.main.controller.ItemsTabController;
import java.util.Date;

/**
 *
 * @author Administrator
 */
public class ViewUpdateItemController {

    private ItemsTabController parentController;
    private ViewUpdateItemWindow window;
    private Item item = null;

    public ViewUpdateItemController(ItemsTabController parentController, String sku) {
        this.parentController = parentController;

        item = DaoFactory.getInstance().getItemDao().findBySerial(sku);
    }

    public void displayWindow() {
        window = new ViewUpdateItemWindow(this);
        window.populateCustomers(DaoFactory.getInstance().getCustomerDao().findAll());
        window.populateWindow(item, DaoFactory.getInstance().getStaffDao().findAll());
        window.showWindow();
    }

    public void fromWindow(String customerName) {
        Customer customer = null;
        if (!customerName.trim().isEmpty()) {
            customer = DaoFactory.getInstance().getCustomerDao().findByName(customerName);

            if (customer == null) {
                customer = new Customer((String) customerName);                
            }
        } else {
            customer = null;
        }

        item.getPurchaseDetail().setCustomer(customer);
        DaoFactory.getInstance().getItemDao().saveOrUpdate(item);
        parentController.refreshTable();
    }

    public void addItemHistory(String status, String staffName, Date dateX) {
        Staff staff = DaoFactory.getInstance().getStaffDao().findByName(staffName);
        ItemStatus itemStatus = new ItemStatus(status, dateX, staff);

        item.addHistory(itemStatus);
        DaoFactory.getInstance().getItemDao().saveOrUpdate(item);
        window.populateItemHistoryTable(item);
    }

    void removeHistory(int row) {
        item.getHistory().remove(item.getHistory().get(row));
        DaoFactory.getInstance().getItemDao().saveOrUpdate(item);

        window.populateItemHistoryTable(item);
    }

    public void deleteItem() {
        DaoFactory.getInstance().getItemDao().delete(item);
        parentController.getParentController().getInventoryTabController().refreshTable();
        parentController.refreshTable();
        parentController.getParentController().getRepairTabController().refreshTable();
    }

    public boolean hasBeenSold() {
        return (item.getPurchaseDetail() != null);
    }
}
